package com.qcby.chatservice.config;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dxy.library.json.jackson.JacksonUtil;
import com.qcby.chatservice.config.properties.RedissonProperties;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.spring.cache.CacheConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * redisson配置
 *
 * @author cong.zhen
 * @date 2023/01/18
 */
@AutoConfigureBefore({RedissonAutoConfiguration.class})
@EnableConfigurationProperties({RedissonProperties.class})
@Configuration
@EnableCaching
@Slf4j
public class RedisConfiguration extends CachingConfigurerSupport {
    private static final String REDIS_PROTOCOL_PREFIX = "redis://";
    private static final String REDISS_PROTOCOL_PREFIX = "rediss://";
    @Resource
    private RedisProperties redisProperties;
    @Resource
    private RedissonProperties redissonProperties;

    public RedisConfiguration() {
    }

    @Primary
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() {
        String prefix = REDIS_PROTOCOL_PREFIX;
        if (this.redisProperties.isSsl()) {
            prefix = REDISS_PROTOCOL_PREFIX;
        }
        Config config = new Config();
        config.setThreads(this.redissonProperties.getThreads()).
                setNettyThreads(this.redissonProperties.getNettyThreads()).
                setCodec(new JsonJacksonCodec(JacksonUtil.getObjectMapper()));
        RedissonProperties.SingleServerConfig singleServerConfig = this.redissonProperties.getSingleServerConfig();
        if (ObjectUtil.isNotNull(singleServerConfig)) {
            config.useSingleServer().setAddress(prefix + this.redisProperties.getHost() + ":" + this.redisProperties.getPort())
                    .setConnectTimeout((int)this.redisProperties.getTimeout().toMillis())
                    .setDatabase(this.redisProperties.getDatabase())
                    .setPassword(StrUtil.isNotBlank(this.redisProperties.getPassword()) ? this.redisProperties.getPassword() : null)
                    .setTimeout(singleServerConfig.getTimeout())
                    .setClientName(singleServerConfig.getClientName())
                    .setIdleConnectionTimeout(singleServerConfig.getIdleConnectionTimeout())
                    .setSubscriptionConnectionPoolSize(singleServerConfig.getSubscriptionConnectionPoolSize())
                    .setConnectionMinimumIdleSize(singleServerConfig.getConnectionMinimumIdleSize())
                    .setConnectionPoolSize(singleServerConfig.getConnectionPoolSize());
        }

        RedissonProperties.ClusterServersConfig clusterServersConfig = this.redissonProperties.getClusterServersConfig();
        if (ObjectUtil.isNotNull(clusterServersConfig)) {
            String finalPrefix = prefix;
            List<String> nodes = this.redisProperties.getCluster().getNodes().stream().map((node) -> finalPrefix + node).collect(Collectors.toList());
            config.useClusterServers().setConnectTimeout((int)this.redisProperties.getTimeout().toMillis())
                    .setPassword(StrUtil.isNotBlank(this.redisProperties.getPassword()) ? this.redisProperties.getPassword() : null)
                    .setTimeout(clusterServersConfig.getTimeout())
                    .setClientName(clusterServersConfig.getClientName())
                    .setIdleConnectionTimeout(clusterServersConfig.getIdleConnectionTimeout())
                    .setSubscriptionConnectionPoolSize(clusterServersConfig.getSubscriptionConnectionPoolSize())
                    .setMasterConnectionMinimumIdleSize(clusterServersConfig.getMasterConnectionMinimumIdleSize())
                    .setMasterConnectionPoolSize(clusterServersConfig.getMasterConnectionPoolSize())
                    .setSlaveConnectionMinimumIdleSize(clusterServersConfig.getSlaveConnectionMinimumIdleSize())
                    .setSlaveConnectionPoolSize(clusterServersConfig.getSlaveConnectionPoolSize())
                    .setReadMode(clusterServersConfig.getReadMode())
                    .setSubscriptionMode(clusterServersConfig.getSubscriptionMode())
                    .setNodeAddresses(nodes);
        }

        RedissonClient redissonClient = Redisson.create(config);
        log.info("初始化 redis 配置");
        return redissonClient;
    }

    @Bean
    public CacheManager cacheManager(RedissonClient redissonClient) {
        List<RedissonProperties.CacheGroup> cacheGroup = this.redissonProperties.getCacheGroup();
        Map<String, CacheConfig> config = new HashMap(8);
        Iterator var4 = cacheGroup.iterator();

        while (var4.hasNext()) {
            RedissonProperties.CacheGroup group = (RedissonProperties.CacheGroup) var4.next();
            CacheConfig cacheConfig = new CacheConfig(group.getTtl(), group.getMaxIdleTime());
            cacheConfig.setMaxSize(group.getMaxSize());
            config.put(group.getGroupId(), cacheConfig);
        }

        return new RedissonSpringCacheManager(redissonClient, config, JsonJacksonCodec.INSTANCE);
    }


}
